﻿var map;
var geocoder;
var address;
var markers = [];
var baseIcon = null;
var prj = null;

function showMarker(i)
{
	GEvent.trigger(markers[i-1], "click");
}

function createBaseIcon()
{
	baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.image = "/static/images/note.png";
	baseIcon.iconSize = new GSize(76, 56);
	baseIcon.shadow = "";
	baseIcon.shadowSize = new GSize(0, 0);
	baseIcon.iconAnchor = new GPoint(38, 28);
	baseIcon.infoWindowAnchor = new GPoint(38, 28);
}

function makeRouteVisible(markers)
{
	var bounds = new GLatLngBounds(); 		
	for (var i = 0; i < markers.length; i++)
	{
		bounds.extend(markers[i]);	
	}
	map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));		 
}

function initialize() 
{
	if (GBrowserIsCompatible()) 
	{
		createBaseIcon();
		map = new GMap2(document.getElementById("map_canvas"));		
		prj = map.getCurrentMapType().getProjection();
		map.setUI(map.getDefaultUI());
		//map.addControl(new google.maps.LocalSearch(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(5,20)));
		geocoder = new GClientGeocoder();
		for (var i = 0; i < locations.length; i++)
		{			
			map.addOverlay(createMarker(locations[i]));
		}
		
		if (locations.length > 0)
		{
			map.setCenter(locations[0], 15);		
			LoadAddresses();
		}
		else
		{
			map.setCenter(new GLatLng(59.939030938985304, 30.315635204315186), 15);
		}
		
		if (logged_in)
		{
			GEvent.addListener(map, 'click', map_onClick);
		}
	}
	drawRoute();
}

function getColor(speed)
{
	if (speed == -1) return "#666666"
	if (speed < 20) return "brown";	
	if (speed < 40) return "orange";
	return "green";
}

function map_onClick(overlay, point)
{		
	if (!point)
	{
		return;
	}
		
	map.openInfoWindowHtml(point, '<div style="margin:10px">(' + point.y + ', ' + point.x  + ')</div>' +
									'<center><form method="POST" action="/Add/">' +
									'<input type="hidden" name="limit" value="' + limit + '">' +
									'<input type="submit" value="Я здесь!">' +
									'<input type="hidden" name="longitude" value="' + point.x + '"/>' + 
									'<input type="hidden" name="latitude" value="' + point.y + '" />' +
									'</form></center>'
								);
}

function drawArrow(pt1, pt2, color)
{
	var lineWidth = 10;
	var lineOpacity = 0.7;
	var arrowSize = 50;

	function addHead(point, theta, zoom, color) 
	{
		var p = prj.fromLatLngToPixel(point,  zoom)
		var x = p.x, y = p.y;
		var t = theta + (Math.PI/4) ;
		if(t > Math.PI)
			t -= 2*Math.PI;
		var t2 = theta - (Math.PI/4) ;
		if(t2 <= (-Math.PI))
			t2 += 2*Math.PI;
		var pts = new Array();
		var headLength = arrowSize;
		var x1 = x-Math.cos(t)*headLength;
		var y1 = y+Math.sin(t)*headLength;
		var x2 = x-Math.cos(t2)*headLength;
		var y2 = y+Math.sin(t2)*headLength;	
		pts.push(prj.fromPixelToLatLng(new GPoint(x1,y1), zoom));
		pts.push(prj.fromPixelToLatLng(new GPoint(x,y), zoom));    
		pts.push(prj.fromPixelToLatLng(new GPoint(x2,y2), zoom));
		var head = new GPolygon(pts, color, 0, 1, color, 1);
		map.addOverlay(head);
	}
	
	function addArrow(point, theta, zoom)	
	{
		var p = prj.fromLatLngToPixel(point,  zoom)
		var x = p.x, y = p.y;		
		var t = theta + (Math.PI/4) ;
		var arrow = new GIcon(G_DEFAULT_ICON);
		arrow.shadow = "";
			arrow.iconAnchor = new GPoint(16, 16);		
        arrow.image = "/static/images/360/arrow_" + parseInt(theta * 180 / Math.PI) + ".png";
		markerOptions = { icon:arrow };
		map.addOverlay(new GMarker(point, markerOptions));
	}

	var polyline = new GPolyline([pt1, pt2], color, lineWidth, lineOpacity);
	var zoom = map.getZoom();
	var p1 = prj.fromLatLngToPixel(pt1,  zoom);
	var p2 = prj.fromLatLngToPixel(pt2,  zoom);
	var dx = p2.x-p1.x;
	var dy = p2.y-p1.y;      
	var theta = Math.atan2(-dy,dx);
  
	//addHead(pt2, theta, zoom, color);
	addArrow(pt2, theta, zoom);
	map.addOverlay(polyline);
}

function drawRoute(pt1, pt2, color)
{	
	for (var i = locations.length - 1; i >= 1; i--)
	{
		var color = getColor(locations[i].speed);
		drawArrow(locations[i], locations[i-1], color);
	}
		
	makeRouteVisible(locations);
}

function createMarker(latlng)
{
	var marker = new GMarker(latlng);
			markers.push(marker);
			GEvent.addListener(marker, "click", function() {				
				marker.openInfoWindowHtml('<div class="hint">' + latlng.time + '<br>' + $("#location" + latlng.index)[0].innerHTML + '<br>' + $("#latlng" + latlng.index)[0].innerHTML + '</div>');
				map.setCenter(latlng);
			});
	return marker
}

function updateScrollPanel()
{	
	$(".scroll-pane").jScrollPane();
}

function closeHint()
{	
	$('.jScrollPaneContainer').height($('.jScrollPaneContainer').height() + $('#syshint').height() + 12);
	$("#syshint")[0].style.display = "none";
	updateScrollPanel();
}

function getAddress(i)
{
	function showAddress(response) 
	{			
		if (!response || response.Status.code != 200) 
		{
			$("#location" + i)[0].innerHTML =  "Нет данных";
		} 
		else 
		{
			place = response.Placemark[0];
			$("#location" + i)[0].innerHTML = response.name;
			// point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
			// marker = new GMarker(point);
			// map.addOverlay(marker);
			// marker.openInfoWindowHtml(
				// '<b>orig latlng:</b>' + response.name + '<br/>' + 
				// '<b>latlng:</b>' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '<br>' +
				// '<b>Status Code:</b>' + response.Status.code + '<br>' +
				// '<b>Status Request:</b>' + response.Status.request + '<br>' +
				// '<b>Address:</b>' + place.address + '<br>' +
				// '<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
				// '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
		}
	}

	var Addresser = function(index)
		{			
			this.showAddress = function(response) 
			{			
				if (!response || response.Status.code != 200) 
				{
					$("#location" + index)[0].innerHTML =  "Нет данных <a href='javascript:getAddress(" + i + ")'>Обновить</a>";
				} 
				else 
				{
					place = response.Placemark[0];
					$("#location" + index)[0].innerHTML = place.address;
				}
				updateScrollPanel();
			}
		}
		
	var adrs = new Addresser(i+1);
	geocoder.getLocations(locations[i], adrs.showAddress);
}

function LoadAddresses()
{	
	for (var i = 0; i < locations.length; i++)
	{			
		getAddress(i);
	}
}